package com.jg.blog.service.impl;

import com.jg.blog.enums.ResultEnum;
import com.jg.blog.enums.StateEnums;
import com.jg.blog.exception.BlogException;
import com.jg.blog.mapper.NoticeMapper;
import com.jg.blog.pojo.Notice;
import com.jg.blog.service.NoticeService;
import com.jg.blog.utils.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * </p>
 *
 * @author 稽哥
 * @date 2020-02-07 14:04:12
 * @Version 1.0
 */
@Service
@Slf4j
public class NoticeServiceImpl implements NoticeService {

    @Autowired
    private NoticeMapper noticeMapper;

    @Override
    public void save(Notice notice) {
        noticeMapper.save(notice);
    }

    @Override
    public void update(Notice notice) {
        noticeMapper.updateById(notice);
    }

    @Override
    public Notice getById(Integer id) {
        return noticeMapper.getById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Notice read() {
        Notice notice = noticeMapper.getNotice();
        if (notice == null) {
            return null;
        }
        // 更新阅读数
        notice.setNoticeRead(notice.getNoticeRead() + 1);
        noticeMapper.updateById(notice);
        return notice;
    }

    @Override
    public void deleteById(Integer id) {
        noticeMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void enableById(Integer id) {
        // 查询是否已经存在启用的关于我的
        Notice notice = noticeMapper.getNotice();
        if (notice != null) {
            throw new BlogException(ResultEnum.ERROR.getCode(), "当前已存在启用中的公告");
        }
        notice = noticeMapper.getById(id);
        notice.setEnable(StateEnums.ENABLED.getCode());
        noticeMapper.updateEnable(notice);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void disableById(Integer id) {
        Notice notice = noticeMapper.getById(id);
        notice.setEnable(StateEnums.NOT_ENABLE.getCode());
        noticeMapper.updateEnable(notice);
    }

    @Override
    public Page<Notice> getByPage(Page<Notice> page) {
        // 查询数据
        List<Notice> noticeList = noticeMapper.getByPage(page);
        page.setList(noticeList);
        // 查询总数
        int totalCount = noticeMapper.getCountByPage(page);
        page.setTotalCount(totalCount);
        return page;
    }
}
